#include "clock_manager.h"
#include "analog_clock.h"

bool maybeUpdateClock(Panel &panel, NTPTime &ntpTime, unsigned long &lastClockUpdate, unsigned long clockIntervalMs) {
    if (millis() - lastClockUpdate <= clockIntervalMs) return false;
    lastClockUpdate = millis();

    uint8_t hour, minute, second, wday;
    if (ntpTime.isTimeValid()) {
        hour = ntpTime.getHour();
        minute = ntpTime.getMinute();
        second = ntpTime.getSecond();
        time_t now = time(nullptr);
        struct tm timeinfo;
        localtime_r(&now, &timeinfo);
        wday = timeinfo.tm_wday; // 0=Sunday
    } else {
        unsigned long totalSeconds = millis() / 1000;
        second = totalSeconds % 60;
        minute = (totalSeconds / 60) % 60;
        hour = (totalSeconds / 3600) % 24;
        // Fake weekday: 0=Sun
        wday = (totalSeconds / 86400 + 4) % 7; // 1970-01-01 was a Thursday
    }

    static const char* WEEKDAYS[] = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};
    const char* weekDayStr = WEEKDAYS[wday % 7];

    // Draw the clock in the left square area
    drawAnalogClock(panel, 0, 0, panel.height, panel.height, hour, minute, second, weekDayStr);
    return true;
}
